import React, { useState, useEffect } from 'react';
import { Alert, Select, Row, Col } from 'antd';
import FormItem from '../../../../../../components/FormItem';
import services from '../../../../../../services/api';

export default function SelectData(props) {
  const { form, value, handleDataSourceChange } = props;
  const { setFieldsValue } = form;
  const [supplierList, setSupplierList] = useState([]);
  const [dataSourceList, setDataSourceList] = useState([]);

  useEffect(() => {
    getSupplierList();
  }, []);

  // 获取供应商
  const getSupplierList = async () => {
    const { data, code } = await services.dataSource.supplierList();
    if (!code) setSupplierList(data);
  };

  const handleSupplierChange = (value) => {
    setFieldsValue({ thirdInterfaceId: undefined });
    value && getListBySupplierId(value);
  };

  const getListBySupplierId = async (id) => {
    const { data, code } = await services.dataSource.listBySupplierId(id);
    if (!code) setDataSourceList(data);
  };

  const getFormItems = () => {
    const { supplierId, thirdInterfaceId } = value;
    const layout = {
      labelCol: {
        span: 6,
      },
      wrapperCol: {
        span: 18,
      },
    };
    return [
      {
        label: {
          label: '供应商',
          ...layout,
        },
        name: 'supplierId',
        options: {
          initialValue: supplierId,
          rules: [{ required: true, message: '请选择供应商' }],
        },
        component: (
          <Select placeholder='请选择供应商' onChange={handleSupplierChange}>
            {supplierList.map((item) => (
              <Select.Option value={item.id} key={item.id}>
                {item.name}
              </Select.Option>
            ))}
          </Select>
        ),
      },
      {
        label: {
          label: '数据源',
          ...layout,
        },
        name: 'thirdInterfaceId',
        options: {
          initialValue: thirdInterfaceId,
          rules: [{ required: true, message: '请选择数据源' }],
        },
        component: (
          <Select placeholder='请选择数据源' onChange={handleDataSourceChange}>
            {dataSourceList.map((item) => (
              <Select.Option value={item.id} key={item.id}>
                {item.name}
              </Select.Option>
            ))}
          </Select>
        ),
      },
    ].filter(Boolean);
  };

  return (
    <>
      <Row type='flex' gutter={20}>
        {getFormItems().map((item) => {
          return (
            <Col span={8} key={item.name}>
              <FormItem form={form} item={item} colNum={1} />
            </Col>
          );
        })}
      </Row>
      <Alert
        message={
          '请求中的所有参数，包括Path中的动态参数，Header参数，Query参数，Body参数（通过Form表单传输的参数），参数名称保证唯一。'
        }
        type='info'
        style={{ marginTop: '20px' }}
      />
    </>
  );
}
